C# 문법 정리
- 문자열 보간 (String interpolation)
- 패턴 매칭
1. 문자열 보간 (String interpolation)
# $ 특수 문자는 문자열을 보간 문자열로 식별합니다.
# $ 와 ” 사이에는 공백이 없어야 합니다.
# 보간 문자열은 복합 포맷 방식보다 더 나은 가독성과 편리한 문법을 제공합니다.
# 복합 포맷 방식과 문자열 보간 방식 비교
string name = "Mark";
var date = DateTime.Now;
// 복합 포맷 방식:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// 문자열 보간
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
# 보간 문자열의 구조
{<interpolationExpression>[,<alignment>][:<formatString>]}
# interpolationExpression : null 값은 String.Empty
# alignment : 최소 문자 개수 (양수는 오른쪽 정렬, 음수는 왼쪽 정렬)
--------------------------------------------------------------------------
Console.WriteLine($"|{"Left",-7}|{"Right",7}|");
const int FieldWidthRightAligned = 20;
Console.WriteLine($"{Math.PI,FieldWidthRightAligned} - default formatting of the pi number");
Console.WriteLine($"{Math.PI,FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");
// Expected output is:
// |Left | Right|
// 3.14159265358979 - default formatting of the pi number
// 3.142 - display only three decimal digits of the pi number
# C# 10 부터 보간 문자열을 사용해서 상수 문자열을 초기화 할 수 있습니다.
# C# 11 부터 보간 문자열에 뉴라인을 포함할 수 있습니다. 다음 예제는 보간 문자열과 패턴 매칭을 사용해서 가독성 향상을 보여줍니다.
string message = $"The usage policy for {safetyScore} is {
safetyScore switch
{
> 90 => "Unlimited usage",
> 80 => "General usage, with daily safety check",
> 70 => "Issues must be addressed within 1 week",
> 50 => "Issues must be addressed within 1 day",
_ => "Issues must be addressed before continued use",
}
}";
# C# 11 부터 raw string literal 사용할 수 있습니다.
int X = 2;
int Y = 3;
var pointMessage = $"""The point "{X}, {Y}" is {Math.Sqrt(X * X + Y * Y)} from the origin""";
Console.WriteLine(pointMessage);
// output: The point "2, 3" is 3.605551275463989 from the origin.
# 여러개의 $ 문자를 사용해서 { 와 }를 이스케이프 시키지 않고 포함할 수 있습니다.
int X = 2;
int Y = 3;
var pointMessage = $$"""The point {{{X}}, {{Y}}} is {{Math.Sqrt(X * X + Y * Y)}} from the origin""";
Console.WriteLine(pointMessage);
// output: The point {2, 3} is 3.605551275463989 from the origin.
# 중괄호의 개수가 $ 의 개수보다 더 적다면 중괄호는 결과에 포함됩니다.
# $ 문자보다 중괄호의 개수가 더 많다면 중괄호는 결과에 포함됩니다.
특수 문자
# 중괄호를 포함하려면 두개의 중괄호를 사용합니다. {{ 또는 }}
# 콜론 (“:”) 은 보간 문자열에서 특별한 의미를 가지므로 삼항 연산자를 사용하려면 괄호를 사용합니다.
# 다음 예제는 중괄호를 포함하는 방법과 삼항연산자 사용하는 방법을 보여줍니다.
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
// Expected output is:
// He asked, "Is your name Horace?", but didn't wait for a reply :-{
// Horace is 34 years old.
# interpolated verbatim string 는 $ 문자와 @ 문자로 시작합니다. 순서는 상관 없고 $@”…” 와 @$”…” 모두 유효합니다.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
2. 패턴 매칭
- is 식
- switch 식
null 체크
다음 예제는 null 체크하면서 nullable 값 형식을 해당 타입으로 변환합니다.
int? maybe = 12;
if (maybe is int number)
{
Console.WriteLine($"The nullable int 'maybe' has the value {number}");
}
else
{
Console.WriteLine("The nullable int 'maybe' doesn't hold a value");
}
위 코드는 선언 패턴입니다. 변수 타입을 테스트하고 새로운 변수에 할당합니다.
이 방법은 null 레퍼런스 값을 체크하면서 not 패턴을 추가하는 것이 이상적인 방법입니다.
string? message = "This is not the null string";
if (message is not null)
{
Console.WriteLine(message);
}
위 예제는 ‘상수 패턴’ 을 사용해서 변수와 null 을 비교했습니다.
타입 테스트
또 다른 일반적인 방법은 주어진 타입과 일치하는지 확인하는 방법입니다.
예를 들어 다음 코드는 변수가 null 이 아니고 IList<T>를 구현하는지 테스트합니다.
아래 코드는 null 을 방지하고 IList 구현하지 않는 타입을 방지합니다.
public static T MidPoint<T>(IEnumerable<T> sequence)
{
if (sequence is IList<T> list)
{
return list[list.Count / 2];
}
else if (sequence is null)
{
throw new ArgumentNullException(nameof(sequence), "Sequence can't be null.");
}
else
{
int halfLength = sequence.Count() / 2 - 1;
if (halfLength < 0) halfLength = 0;
return sequence.Skip(halfLength).First();
}
}
불연속 값 비교
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns